package net.aiion.weave.util.cryptography;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1
{
    private final byte[] inputBytes;

    public SHA1(final byte[] aBytes) {
        inputBytes = aBytes;
    }

    public SHA1(final String aString) {
        try {
            inputBytes = aString.getBytes("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new CryptographyException(ex);
        }
    }

    public byte[] calculateBytes() {
        try {
            final MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            messageDigest.update(inputBytes);
            return messageDigest.digest();
        } catch (final NoSuchAlgorithmException e) {
            throw new CryptographyException(e);
        }
    }

    public String calculateString() {
        try {
            return HexadecimalConverter.convertBytesToHexString(calculateBytes());
        } catch (final UnsupportedEncodingException e) {
            throw new CryptographyException(e);
        }
    }

    public static byte[] calculateBytes(final byte[] aBytes) {
        return new SHA1(aBytes).calculateBytes();
    }

    public static byte[] calculateBytes(final String aString) {
        return new SHA1(aString).calculateBytes();
    }

    public static String calculateString(final byte[] aBytes) {
        return new SHA1(aBytes).calculateString();
    }

    public static String calculateString(final String aString) {
        return new SHA1(aString).calculateString();
    }
}
